//
//  KKConversationItem.m
//  ReplyAssistant
//
//  Created by liaozhenming on 2018/11/22.
//  Copyright © 2018 KK. All rights reserved.
//

#import "KKConversationItem.h"
#import "KKMessageItem.h"
#import "RAChatKit/RAMessage.h"

#import "KKRequest/KKNetworkRequest+V1.h"

static NSTimeInterval KKMessage_Time_Interval = 60 * 60 * 12;

@implementation KKConversationItem

+ (instancetype)itemWithJson:(NSDictionary*)json {
    KKConversationItem *item = [KKConversationItem new];
    if ([json isKindOfClass: [NSDictionary class]]) {
        NSString *identifier = json[@"id"];
        NSDictionary *customer = json[@"customer"];
        NSDictionary *lastMessage = json[@"lastMessage"];
        NSInteger badge = [json[@"badge"] intValue];
        
        item.badge = badge;
        item.identifier = identifier;
        item.kk_customer = [RASender itemWithJson: customer];
        
        RAMessage *tmpMessage = [RAMessage itemWithJson: lastMessage];
        item.lastMessage = [KKMessageItem msgWithTMessage: tmpMessage];
    }
    return item;
}

- (instancetype)init {
    self = [super init];
    if (self) {
        self.msgList = [NSMutableArray array];
    }
    return self;
}

- (NSArray*)sendMessage:(KKMessageItem*)msg succ:(RASuccess)succ fail:(RAFail)fail {
    
    __weak typeof(self) weakSelf = self;
    msg.status = KKMessageStatus_Sending;
    NSArray *tmpArray = [weakSelf private_addMsgToList: msg];
    KKNetworkRequest *request = [KKNetworkRequest request_replyContentWithParmeters: msg.msg.parmeters receiveId: self.identifier];
    [KKNetworking sendRequest: request responseCallBack:^(id response, NSString *error) {
        if (error) {
            msg.status = KKMessageStatus_SendFail;
            if (fail) {
                fail(1,error);
            }
            return;
        }
        msg.status = KKMessageStatus_SendSuccess;
        if (succ) {
            succ(@[msg]);
        }
    }];
    return tmpArray;
}

//  发送图片消息
- (NSArray*)sendImageMessage:(KKMessageItem*)msg succ:(nullable RASuccess)succ fail:(nullable RAFail)fail{
    __weak typeof(self) weakSelf = self;
    msg.status = KKMessageStatus_Sending;
    NSArray *tmpArray = [weakSelf private_addMsgToList: msg];
    
    RAImageMessage *imageMessage = (RAImageMessage*)msg.msg;
    
    __weak RAImageMessage *weakImageMessage = imageMessage;
    [KKNetworking uploadImage: imageMessage.image parmeters: nil progress:^(float progress) {
        weakImageMessage.progress = progress;
    } responseCallBack:^(id response, NSString *error) {
        if ([response isKindOfClass: [NSString class]]) {
            //  上传成功
            weakImageMessage.imgPath = (NSString*)response;
            
            KKNetworkRequest *request = [KKNetworkRequest request_replyContentWithParmeters: weakImageMessage.parmeters receiveId: weakSelf.identifier];
            [KKNetworking sendRequest: request responseCallBack:^(id response, NSString *error) {
                if (error) {
                    msg.status = KKMessageStatus_SendFail;
                    if (fail) {
                        fail(1,error);
                    }
                    return;
                }
                msg.status = KKMessageStatus_SendSuccess;
                if (succ) {
                    succ(@[msg]);
                }
            }];
        }
    }];
    
    return tmpArray;
}

- (void)receiveMessage:(KKMessageItem*)msg {
    NSMutableArray *array = [self private_addMsgToList: msg];
    
    if (self.receiveMsgHandle) {
        self.receiveMsgHandle(array);
    }
}

//  获取历史数据
- (void)loadHistoryMessages:(NSArray*)messages {
    [self.msgList removeAllObjects];
    if (messages.count == 0) {
        return;
    }
    
    NSMutableArray *array = [NSMutableArray array];
    NSInteger index = 0;
    
    BOOL lastMsg = true;
    RAMessage *temp = nil;
    do{
        RAMessage *msg = messages[index];
        NSDate *date = msg.timeDate;
        KKMessageItem *imMsg = [KKMessageItem msgWithTMessage: msg];
        if (imMsg) {
            if (lastMsg) {
                lastMsg = false;
                KKMessageItem *timeTip = [KKMessageItem msgWithDate: date];
                [array addObject: timeTip];
            }
            
            if (temp) {
                NSDate *lastDate = temp.timeDate;
                NSTimeInterval timeinterval = [date timeIntervalSinceDate: lastDate];
                if (timeinterval > KKMessage_Time_Interval) {
                    KKMessageItem *timeTip = [KKMessageItem msgWithDate: date];
                    [array addObject: timeTip];
                }
            }
            temp = msg;
            [array addObject: imMsg];
        }
        index++;
    }
    while (index < messages.count);
    [_msgList addObjectsFromArray: array];
}

- (NSMutableArray*)private_addMsgToList:(KKMessageItem*)messageItem {
    if (messageItem) {
        NSMutableArray *array = [NSMutableArray array];
        KKMessageItem *timeTips = [self private_timeTipsOnNewMessage: messageItem];
        if (timeTips) {
            [array addObject: timeTips];
        }
        self.lastMessage = messageItem;
        [array addObject: messageItem];
        [_msgList addObjectsFromArray: array];
        return array;
    }
    return nil;
}

- (KKMessageItem*)private_timeTipsOnNewMessage:(KKMessageItem*)messageItem {
    if (_lastMessage) {
        NSDate *lastDate = _lastMessage.msg.timeDate;
        NSDate *followDate = messageItem.msg.timeDate;
        
        NSTimeInterval timeinterval = [followDate timeIntervalSinceDate:lastDate];
        if (timeinterval > KKMessage_Time_Interval) {
            // 大于1天
            KKMessageItem *msg = [KKMessageItem msgWithDate:followDate];
            return msg;
        }
    }
    return nil;
}

@end
